# -*- coding: utf-8 -*-

import DataModel
import ConfigManager
from Tkinter import *
from SpreadSheet import *
import ttk
import Tix
import tkFileDialog
import tkMessageBox
import os


class PluginsEditor(Toplevel):
    
    def __init__(self, parent, model):
        self.parent = parent
        self.root = parent.parent
        self.model = model
        self.model.initPluginManager()
        Toplevel.__init__(self,self.root)        
        self.pluginsPath = StringVar()
        self.pluginsPath.set(os.path.abspath(self.model.pluginManager.getPluginPath()))        
        self.dbFilePath = StringVar()
        if self.model.databasePath:
            self.dbFilePath.set(self.model.databasePath)
        else:
            self.dbFilePath.set("")
        self.dbDirectoryPath = StringVar()
        if self.model.databasePath:
            self.dbDirectoryPath.set(self.model.databasePath)
        else:
            self.dbDirectoryPath.set("")
        self.diseasesPath = StringVar()
        self.diseasesPath.set(os.path.abspath(self.model.initialDiseasesPath))

        self.title("Databases Options")
        self.optionPanelIn = None

        title_label = ttk.Label(self, text="Choose a database or generate a new one, then press OK")        
        self.ok_button = ttk.Button(self, text="OK", command=self.validate)
        self.isGenerate = BooleanVar()
        self.frame_radio = ttk.Frame(self)
        radio_database = ttk.Radiobutton(self.frame_radio, text="Use existing database:", variable=self.isGenerate, command=self.onRadioChange, value=False)
        radio_generate = ttk.Radiobutton(self.frame_radio, text="Generate new database", variable=self.isGenerate, command=self.onRadioChange, value=True)
        radio_database.grid(row=0, column=0, sticky="wnes")
        radio_generate.grid(row=1, column=0, sticky="wnes")
        self.frame_radio.rowconfigure(1, weight=1)
        self.frame_database = ttk.Frame(self)
        self.frame_generate = ttk.Frame(self)

        title_label.pack(side="top", anchor="center", padx=16, pady=16)
        self.ok_button.pack(side="bottom", padx=16, pady=16)
        self.frame_radio.pack(side="left", fill="y", padx=16, pady=16)
        self.frame_database.pack(side="top", fill="x", padx=16, pady=16)
        self.frame_generate.pack(fill="both", expand=1, padx=16, pady=16)

        # frame_db configuration
        db_entry = ttk.Entry(self.frame_database, textvariable=self.dbFilePath)
        browse_db_button = ttk.Button(self.frame_database, text="Browse...", command=self.browseDatabaseFile)
        db_entry.grid(row=0, column=0, sticky="we")
        browse_db_button.grid(row=0, column=1, sticky="we")
        self.frame_database.columnconfigure(0, weight=1)

        # frame_generate configuration
        plugins_label = ttk.Label(self.frame_generate, text="Plugins path: ")
        plugins_entry = ttk.Entry(self.frame_generate, textvariable=self.pluginsPath)
        browse_plugins_button = ttk.Button(self.frame_generate, text="Browse...", command=self.browsePluginsDirectory)
        path_label = ttk.Label(self.frame_generate, text="New database path: ")
        path_entry = ttk.Entry(self.frame_generate, textvariable=self.dbDirectoryPath)
        browse_path_button = ttk.Button(self.frame_generate, text="Browse...", command=self.browseDatabaseDirectory)
        diseases_label = ttk.Label(self.frame_generate, text="Disease file: ")
        diseases_entry = ttk.Entry(self.frame_generate, textvariable=self.diseasesPath)
        browse_diseases_button = ttk.Button(self.frame_generate, text="Browse...", command=self.browseDiseaseFile)
        list_label = ttk.Label(self.frame_generate, text="Plugins available")
        self.dbHandlersList = Listbox(self.frame_generate)
        self.dbHandlersList.bind('<<ListboxSelect>>',self.pluginSelectedCmd)
        active_label = ttk.Label(self.frame_generate, text="Plugins loaded")
        self.dbHanldersActive = Listbox(self.frame_generate)
        self.dbHanldersActive.bind('<<ListboxSelect>>',self.activePluginSelectedCmd)
        delete_button = ttk.Button(self.frame_generate, text="Disable plugin", command=self.removePlugin)
        generate_button = ttk.Button(self.frame_generate, text="GENERATE\nDATABASE", command=self.generate)

        self.printPlugins()
        self.printActivePlugins()
        self.configPluginFrame = ttk.Frame(self.frame_generate)
        self.optionPanelFrame = ttk.Frame(self.configPluginFrame)
        self.optionPanelFrame.pack(fill="both", expand=1, padx=8, pady=8)
        self.configPluginFrame.grid(row=5, column=1, sticky="wnes")

        plugins_label.grid(row=0, column=0, sticky="e")
        plugins_entry.grid(row=0, column=1, columnspan=2, sticky="we", padx=8, pady=8)
        browse_plugins_button.grid(row=0, column=3, sticky="we")
        path_label.grid(row=1, column=0, sticky="e")
        path_entry.grid(row=1, column=1, columnspan=2, sticky="we", padx=8)
        browse_path_button.grid(row=1, column=3, sticky="we")
        diseases_label.grid(row=3, column=0, sticky="e")
        diseases_entry.grid(row=3, column=1, columnspan=2, sticky="we", padx=8, pady=8)
        browse_diseases_button.grid(row=3, column=3, sticky="we")
        list_label.grid(row=4, column=0)
        self.dbHandlersList.grid(row=5, column=0, sticky="wnes")
        active_label.grid(row=4, column=2)
        self.dbHanldersActive.grid(row=5, column=2, sticky="wnes")
        delete_button.grid(row=6, column=2, sticky="we")
        generate_button.grid(row=5, column=3, sticky="wnes", padx=16, pady=16)
        self.frame_generate.rowconfigure(5, weight=1)
        self.frame_generate.columnconfigure(0, weight=1)
        self.frame_generate.columnconfigure(1, weight=1)
        self.frame_generate.columnconfigure(2, weight=1)


        self.protocol("WM_DELETE_WINDOW", self.quit)
        self.focus()

        self.isGenerate.set(False)
        self.onRadioChange()

    def onRadioChange(self): 
        if(self.isGenerate.get()):
            self.parent.parent.setState(self.frame_database, "disabled")
            self.parent.parent.setState(self.frame_generate, "active")
            self.ok_button.config(state="disabled")
        else:
            self.parent.parent.setState(self.frame_database, "active")
            self.parent.parent.setState(self.frame_generate, "disabled")
            self.ok_button.config(state="active")
            self.optionPanelFrame.destroy()
            self.optionPanelFrame = ttk.Frame(self.configPluginFrame)
            self.optionPanelFrame.pack(fill="both", expand=1, padx=8, pady=8)

    def quit(self):
        self.root.configWindowActive = False
        self.model.saveDatabasePath()
        self.root.setState(self.root, "active")
        self.destroy()
    
    def validate(self):
        self.model.databasePath = self.dbFilePath.get()
        self.model.diseasesPath = self.diseasesPath.get()
        self.quit()

    def generate(self):
        self.parent.parent.setState(self.frame_generate, "disabled")
        self.dbFilePath.set(os.path.abspath(self.dbDirectoryPath.get()))
        self.model.createDatabase(self.dbFilePath.get(), self.diseasesPath.get())
        self.isGenerate.set(False)
        self.onRadioChange()
        
    def printPlugins(self):
        self.plugins=[]
        self.dbHandlersList.delete(0, END)
        for key in self.model.pluginManager.getPlugins().keys():
            self.dbHandlersList.insert(END,key)
            self.plugins.append(key)
    
    def printActivePlugins(self):
        self.activePlugins=[]
        self.dbHanldersActive.delete(0, END)
        for key in self.model.pluginManager.importedDatabaseHandlerPlugins.keys():
            self.dbHanldersActive.insert(END,key)
            self.activePlugins.append(key)
        
    
    def reloadPlugins(self):
        directory = self.dbPath.get()
        if os.path.isdir(directory)==False:
            tkMessageBox.showerror("Open directory","Cannot open this directory",parent =self)
            return
        self.model.pluginManager.setPluginPath(directory)
        self.model.pluginManager.reloadPlugins()
        self.printPlugins()
        self.printActivePlugins()
        if self.dbHandlersList.size()==0:
            tkMessageBox.showwarning("No Plugin","No Plugin found in\n (%s)" % directory,parent=self)
            return
        
    def browsePluginsDirectory(self):
        self.dir_opt = options = {}
        options['initialdir'] = self.pluginsPath.get()
        options['mustexist'] = True
        options['title'] = 'Select Plugins Directory Folder:'
        options['parent'] = self
        directory = tkFileDialog.askdirectory(**self.dir_opt)
        if directory != None and directory!="":
            self.pluginsPath.set(directory)
            self.model.pluginManager.importedDatabaseHandlerPlugins.clear()
            self.reloadPlugins()

    def browseDatabaseDirectory(self):
        self.dir_opt = options = {}
        options['filetypes'] = [('excel files', '.xls')]
        options['initialfile'] = self.dbDirectoryPath.get()
        options['title'] = 'Select Database file:'
        options['parent'] = self
        directory = tkFileDialog.asksaveasfilename(**self.dir_opt)
        if directory != None and directory!="":
            self.dbDirectoryPath.set(directory)

    def browseDatabaseFile(self):
        self.dir_opt = options = {}
        options['initialdir'] = self.dbFilePath.get()
        options['title'] = 'Select Database File:'
        options['parent'] = self
        fileName = tkFileDialog.askopenfilename(**self.dir_opt)
        if fileName != None and fileName!="":
            self.dbFilePath.set(fileName)

    def browseDiseaseFile(self):
        self.dir_opt = options = {}
        options['initialdir'] = self.dbDirectoryPath.get()
        options['title'] = 'Select Disease File:'
        options['parent'] = self
        fileName = tkFileDialog.askopenfilename(**self.dir_opt)
        if fileName != None and fileName!="":
            self.diseasesPath.set(fileName)
    
    def clearOptionPanel(self):
        if self.optionPanelIn != None:
            self.optionPanelIn.destroy()
    
    def pluginSelectedCmd(self,event):
        if(self.isGenerate.get()):
            try:
                selectedItem = self.dbHandlersList.curselection()[0]
            except:
                    pass
            else:
                    selectedItem = int(selectedItem)
                    selectedItem= self.plugins[selectedItem]               
                    currentSelectedClass= self.model.pluginManager.getPlugins()[selectedItem]
                    self.selectedItemName= currentSelectedClass.__name__
                    self.currentInstance = currentSelectedClass()
                    self.clearOptionPanel()
                    self.optionPanelIn = self.currentInstance.getOptionPanel(self.optionPanelFrame)
                    self.currentInstance.setConfigDoneFunction(self.configPluginDone)      
    
    def activePluginSelectedCmd(self,event):
        if(self.isGenerate.get()):
            try:
                selectedItem = self.dbHanldersActive.curselection()[0]
            except:
                    pass
            else:
                    selectedItem = int(selectedItem)
                    selectedItem= self.activePlugins[selectedItem]  
                    self.selectedItemName= selectedItem
                    self.currentInstance= self.model.pluginManager.importedDatabaseHandlerPlugins[selectedItem]
                    self.clearOptionPanel()
                    self.optionPanelIn = self.currentInstance.getOptionPanel(self.optionPanelFrame)
                    self.currentInstance.setConfigDoneFunction(self.configPluginDone)
    
    def configPluginDone(self):
        self.model.pluginManager.importedDatabaseHandlerPlugins[self.selectedItemName]=self.currentInstance
        self.printActivePlugins()
        self.clearOptionPanel()
    
                
    def removePlugin(self):
         try:
                selectedItem = self.dbHanldersActive.curselection()[0]
         except:
             pass
         else:
                  selectedItem = int(selectedItem)
                  selectedItem= self.activePlugins[selectedItem]  
                  del self.model.pluginManager.importedDatabaseHandlerPlugins[selectedItem]
                  self.clearOptionPanel()
                  self.printActivePlugins()


class InputFrame(ttk.Frame):
    def __init__(self, parent, model, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.model = model

        self.label_title = ttk.Label(self, text="Genes of fusion:")
        self.label_title.grid(row=0, column=0, columnspan=2, sticky="w")

        self.label_a = ttk.Label(self, text="Gene A:")
        self.label_a.grid(column=0, row=1, sticky="w")
        self.entry_a = ttk.Entry(self)
        self.entry_a.grid(column=1, row=1, sticky="we")
        self.label_b = ttk.Label(self, text="Gene B:")
        self.label_b.grid(column=0, row=2, sticky="w")
        self.entry_b = ttk.Entry(self)
        self.entry_b.grid(column=1, row=2, sticky="we")
        self.columnconfigure(1, weight=1)

    def processGenesRead(self):
        self.model.nameGeneA = None
        self.model.nameGeneB = None
        if(self.entry_a.get() == "" and self.entry_b.get() == ""):
            return False
        else:
            if self.entry_a.get() != "":
                self.model.nameGeneA = self.entry_a.get()
            if self.entry_b.get()!= "":
                self.model.nameGeneB = self.entry_b.get()
            print "# %s / %s" % (self.model.nameGeneA, self.model.nameGeneB)
            return True
        

class ConfigFrame(ttk.Frame):
    def __init__(self, parent, model, *args, **kwargs):
        ttk.Frame.__init__(self, parent,*args, **kwargs)
        self.parent = parent        
        self.model=model

        self.button_start = ttk.Button(self, text="  START\nPROCESS", command=self.startProcess)
        self.button_start.pack(side="right", fill="y", padx=6, pady=6)
        self.button_databases = ttk.Button(self, text=" Manage\nDatabases", command=self.openPluginDatabaseEditor)
        self.button_databases.pack(side="right", fill="y", padx=6, pady=6)
        self.input_frame = InputFrame(self, self.model)
        self.input_frame.pack(side="left", fill="both", expand=1, padx=6, pady=6)

    def startProcess(self):
        print "# Try to read the 2 input gene names..."
        if not self.input_frame.processGenesRead():
            print "ERROR : Read of the 2 input gene names failed!"        
        print "# Check for global database..."
        if not self.checkForGlobalDatabase():
            print "ERROR : There is no global database!"    
        self.parent.populateResultsFrame()

    def checkForGlobalDatabase(self):
        if not self.model.databasePath:
            self.model.databasePath = os.path.abspath(self.model.initialDatabasePath)
            if self.model.databasePath == "":
                return False
        return True

    def openPluginDatabaseEditor(self):
        if self.parent.configWindowActive == False:
            self.parent.setState(self.parent.parent, "disabled")
            self.pluginsEditor = PluginsEditor(self, self.model)
            self.parent.configWindowActive =True
        else:
            self.pluginsEditor.focus()


class GeneFrame(ttk.Frame):

    def __init__(self, parent, title, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.title = title

        self.title = ttk.Label(self, text=self.title)
        self.title.grid(row=0, column=0)
        self.gene_text = Text(self, height=8, bg="#DDDDDD")
        self.gene_text.grid(row=1, column=0)
        self.scrollbar = ttk.Scrollbar(self, command=self.gene_text.yview)
        self.scrollbar.grid(row=1, column=1, sticky="ns")
        self.gene_text["yscrollcommand"] = self.scrollbar.set
        self.gene_text.configure(state="disabled")
        self.rowconfigure(1, weight=1)
        self.columnconfigure(0, weight=1)

    # self.fusion_text.bind('<Enter>', self.click_context.onFocus)

    def populateGeneFrame(self, respond):
        self.gene_text.configure(state="normal")
        self.gene_text.insert(END, "# NAME: " + respond.name + "\n")
        self.gene_text.insert(END, "# FUNCTION: " + respond.function + "\n")
        self.gene_text.insert(END, "# CHROMOSOME: " + str(respond.chromosome) + "\n")
        self.gene_text.insert(END, "# DISEASE: " + respond.disease + "\n")
        self.gene_text.insert(END, "# LOCUS: " + respond.locus + "\n")
        self.gene_text.configure(state="disabled")

    def clearGeneFrame(self):
        self.gene_text.configure(state="normal")
        self.gene_text.delete(1.0, END)
        self.gene_text.configure(state="disabled")


class PageFrame(ttk.Frame):
    def __init__(self, parent, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        self.ssw = Spreadsheet(self)
        self.ssw.pack(fill="both", expand=1)


class ResultsFrame(ttk.Frame):
    def __init__(self, parent, model, *args, **kwargs):
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        self.model = model
        self.nameGeneA = None
        self.nameGeneB = None
        self.listOfFusionsA = None
        self.listOfFusionsB = None
        self.listOfFusionsAB = None
        
        self.tabbed_frame = ttk.Notebook(self)
        self.tab_fusions_a = PageFrame(self.tabbed_frame)
        self.tab_fusions_b = PageFrame(self.tabbed_frame)
        self.tab_fusions_ab = PageFrame(self.tabbed_frame)
        self.tabbed_frame.add(self.tab_fusions_a, text="Fusions gene A")
        self.tabbed_frame.add(self.tab_fusions_b, text="Fusions gene B")
        self.tabbed_frame.add(self.tab_fusions_ab, text="Fusions genes A/B")
        self.tabbed_frame.grid(row=1, column=0, columnspan=3, sticky="wnes", padx=6, pady=6)

        # Fusion frame configuration
        self.fusion_frame = ttk.Frame(self)
        self.fusion_label_number = ttk.Label(self.fusion_frame, text="# fusions")
        self.fusion_label_between = ttk.Label(self.fusion_frame, text="between")
        self.fusion_label_ga = ttk.Label(self.fusion_frame, text="Gene A")
        self.fusion_label_and = ttk.Label(self.fusion_frame, text="and")
        self.fusion_label_gb = ttk.Label(self.fusion_frame, text="Gene B")
        self.fusion_label_number.grid(row=0, column=0, sticky="s")
        self.fusion_label_between.grid(row=1, column=0)
        self.fusion_label_ga.grid(row=2, column=0)
        self.fusion_label_and.grid(row=3, column=0)
        self.fusion_label_gb.grid(row=4, column=0, sticky="n")
        self.fusion_frame.rowconfigure(0, weight=1)
        self.fusion_frame.rowconfigure(4, weight=1)


        self.gene_frame_a = GeneFrame(self, "Informations gene A")
        self.gene_frame_b = GeneFrame(self, "Informations gene B")

        self.fusion_frame.grid(row=0, column=1, sticky="wnes", padx=6, pady=6)
        self.gene_frame_a.grid(row=0, column=0, sticky="wnes", padx=6, pady=6)
        self.gene_frame_b.grid(row=0, column=2, sticky="wnes", padx=6, pady=6)
        self.grid_columnconfigure(0, weight=1, uniform="unique_size")
        self.grid_columnconfigure(2, weight=1, uniform="unique_size")
        self.grid_rowconfigure(1, weight=1)



    def populate(self):
        self.clearFramesAndFusions()
        print "# Try to read global database..."
        self.model.readDatabase(self.model.databasePath)
        print "# Request gene A, B, and fusions between A and B..."
        
        respond = self.model.makeRequest(self.model.nameGeneA, self.model.nameGeneB)
        
        if not self.model.nameGeneA or not respond[0]:
            print "ERROR : Gene A does not exist!"
            self.nameGeneA = "Gene A"
        else:   
            self.gene_frame_a.populateGeneFrame(respond[0])
            self.nameGeneA = respond[0].name
            respondA = self.model.makeRequest(self.model.nameGeneA, None)
            if not respondA[2]:                
                print "ERROR : Gene A does not have fusions!"
            else:
                self.listOfFusionsA = respondA[2]
                self.populateAFusions()

        if not self.model.nameGeneB or not respond[1]:
            print "ERROR : Gene B does not exist!"
            self.nameGeneB = "Gene B"
        else:
            self.gene_frame_b.populateGeneFrame(respond[1])
            self.nameGeneB = respond[1].name
            respondB = self.model.makeRequest(self.model.nameGeneB, None)
            if not respondB[2]:                
                print "ERROR : Gene B does not have fusions!"
            else:
                self.listOfFusionsB = respondB[2]
                self.populateBFusions()

        if not self.model.nameGeneA or not self.model.nameGeneB or not respond[0] or not respond[1] or not respond[2]:
            print "ERROR : No fusion between gene A and B!"
            numberOfFusions = 0
        else:
            self.listOfFusionsAB = respond[2]
            numberOfFusions = len(self.listOfFusionsAB)
            self.populateABFusions()

        self.populateFusionFrame(numberOfFusions)


    def populateFusionFrame(self, numberOfFusions):
        self.fusion_label_number.config(text=str(numberOfFusions) + " fusions")
        self.fusion_label_ga.config(text=self.nameGeneA)
        self.fusion_label_gb.config(text=self.nameGeneB)

    def populateABFusions(self):
        if len(self.listOfFusionsAB) > 0:
            self.tab_fusions_ab.ssw.initialise()
            self.tab_fusions_ab.ssw.addColumn("Name gene A")
            self.tab_fusions_ab.ssw.addColumn("Breakpoint A")
            self.tab_fusions_ab.ssw.addColumn("Strand A")
            self.tab_fusions_ab.ssw.addColumn("Direction A")
            self.tab_fusions_ab.ssw.addColumn("Name gene B")
            self.tab_fusions_ab.ssw.addColumn("Breakpoint B")
            self.tab_fusions_ab.ssw.addColumn("Strand B")
            self.tab_fusions_ab.ssw.addColumn("Direction B")
            self.tab_fusions_ab.ssw.addColumn("Notes")

            for fusion in self.listOfFusionsAB:
                ia = fusion.informationA
                ib = fusion.informationB
                self.tab_fusions_ab.ssw.addRow(Tkinter.END, (fusion.geneA, ia.breakpoint, ia.strand, ia.fusionDirection, fusion.geneB, ib.breakpoint, ib.strand, ib.fusionDirection, fusion.notes))

            self.tab_fusions_ab.ssw.show()


    def populateAFusions(self):
        if len(self.listOfFusionsA) > 0:
            self.tab_fusions_a.ssw.initialise()
            self.tab_fusions_a.ssw.addColumn("Name gene A")
            self.tab_fusions_a.ssw.addColumn("Breakpoint A")
            self.tab_fusions_a.ssw.addColumn("Strand A")
            self.tab_fusions_a.ssw.addColumn("Direction A")
            self.tab_fusions_a.ssw.addColumn("Name gene X")
            self.tab_fusions_a.ssw.addColumn("Breakpoint X")
            self.tab_fusions_a.ssw.addColumn("Strand X")
            self.tab_fusions_a.ssw.addColumn("Direction X")
            self.tab_fusions_a.ssw.addColumn("Notes")

            for fusion in self.listOfFusionsA:
                ia = fusion.informationA
                ib = fusion.informationB
                self.tab_fusions_a.ssw.addRow(Tkinter.END, (fusion.geneA, ia.breakpoint, ia.strand, ia.fusionDirection, fusion.geneB, ib.breakpoint, ib.strand, ib.fusionDirection, fusion.notes))

            self.tab_fusions_a.ssw.show()

    def populateBFusions(self):
        if len(self.listOfFusionsB) > 0:
            self.tab_fusions_b.ssw.initialise()
            self.tab_fusions_b.ssw.addColumn("Name gene B")
            self.tab_fusions_b.ssw.addColumn("Breakpoint B")
            self.tab_fusions_b.ssw.addColumn("Strand B")
            self.tab_fusions_b.ssw.addColumn("Direction B")
            self.tab_fusions_b.ssw.addColumn("Name gene X")
            self.tab_fusions_b.ssw.addColumn("Breakpoint X")
            self.tab_fusions_b.ssw.addColumn("Strand X")
            self.tab_fusions_b.ssw.addColumn("Direction X")
            self.tab_fusions_b.ssw.addColumn("Notes")

            for fusion in self.listOfFusionsB:
                ia = fusion.informationA
                ib = fusion.informationB
                self.tab_fusions_b.ssw.addRow(Tkinter.END, (fusion.geneA, ia.breakpoint, ia.strand, ia.fusionDirection, fusion.geneB, ib.breakpoint, ib.strand, ib.fusionDirection, fusion.notes))

            self.tab_fusions_b.ssw.show()


    def clearFramesAndFusions(self):        
        self.nameGeneA = None
        self.nameGeneB = None
        self.listOfFusionsA = None
        self.listOfFusionsB = None
        self.listOfFusionsAB = None
        self.gene_frame_a.clearGeneFrame()
        self.gene_frame_b.clearGeneFrame()
        self.tab_fusions_a.ssw.initialise()
        self.tab_fusions_a.ssw.show()
        self.tab_fusions_b.ssw.initialise()
        self.tab_fusions_b.ssw.show()
        self.tab_fusions_ab.ssw.initialise()
        self.tab_fusions_ab.ssw.show()


    def onAClickPopulateAFusions(self):
        # Method to pass to Gene A frame
        pass

    def onBClickPopulateBFusions(self):
        # Method to pass to Gene B frame
        pass


class ErrorFrame(Frame):
    def __init__(self,parent, *args, **kw):
        Frame.__init__(self,parent, *args, **kw)
        self.parent =parent
        self.parent.model.setErrorHandler(self.printException)
        scrollbar = Scrollbar(self)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.text = Text(self,height=7,wrap=WORD, yscrollcommand=scrollbar.set)
        self.text.pack(fill=BOTH,expand=TRUE)

        scrollbar.config(command=self.text.yview)
    
    def printException(self,exc, val, tb):
        text = "Error: %s: %s.\n" % (str(type(val)),str(val))
        self.text.insert(END,text)
        # tb = traceback.format_exc()
        # self.text.insert(END,tb)
        
    def clear(self):
        self.text.delete(1.0,END)


class MainFrame(ttk.Frame):
    
    def __init__(self, parent, model, *args, **kwargs):
        ttk.Frame.__init__(self, parent,*args, **kwargs)
        self.debugMode=True
        self.parent = parent
        self.parent.title("pyFusion")
        self.model=model        
        self.configWindowActive = False
        parent.report_callback_exception = self.model.handleError

        self.config_frame = ConfigFrame(self, self.model)
        self.config_frame.pack(side="top", fill="x")

        self.results_frame = ResultsFrame(self, self.model)
        self.results_frame.pack(fill="both", expand=1)

        self.configTtkBackgrounds()
        
        if self.debugMode==False:
            self.errorFrame =ErrorFrame(self)
            self.errorFrame.pack(side="bottom",fill=X)
        
        self.centerWindow()
        self.pack(side=TOP,fill=BOTH,expand=TRUE)

        self.model.restoreDatabasePath()


    def populateResultsFrame(self):
        self.results_frame.populate()
        

    def configTtkBackgrounds(self):
        s = ttk.Style()
        defaultStyle = s.theme_use()
        s.configure('Debug.TFrame', background='green')
        s.configure('Db.TFrame', background='white')
        
    def centerWindow(self):
        w = 800
        h = 600
        sw = self.winfo_screenwidth()
        sh = self.winfo_screenheight()     
        x = (sw - w)/2
        y = (sh - h)/2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
        
    def refresh(self):
        if self.debugMode ==False:
            self.errorFrame.clear()
                                                
    def handleCloseEvent(self):
        self.parent.destroy()

    def setState(self, widget, state="disabled"): 
        try: 
            widget.config(state=state) 
        except TclError:   # not sure what exception will be raised 
            if state=="active":
                try: 
                    widget.config(state="normal") 
                except TclError:   # not sure what exception will be raised 
                    pass 
        for child in widget.winfo_children(): 
            self.setState(child, state=state)



def main():
    root = Tix.Tk()
    model = DataModel.PyFusion()
    MainFrame(root, model)
    root.mainloop()  

if __name__ == '__main__':
    main()
